package com.brsya.autonat.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

import com.alibaba.fastjson.JSON;
import com.brsya.autonat.MyApplication;
import com.brsya.autonat.R;
import com.brsya.autonat.bean.SignalBean;
import com.brsya.autonat.constant.Constant;
import com.brsya.autonat.receive.BluetoothStateBroadcastReceive;
import com.brsya.autonat.ui.MainActivity;
import com.brsya.autonat.util.LogUtil;

/**
 * Created by Brsya
 * CreateDate: 2023/2/11  21:10
 * Description:
 * 保留后台服务
 */
public class MyService extends Service {

    private static final int ONGOING_NOTIFICATION_ID = 1500;

    private TextView tvSignal;

    private PhoneStateListener phoneStateListener;
    private TelephonyManager mTelephonyManager;
    private Handler mainHandler;
    private Runnable refreshSignalRunnable;

    @Override
    public void onCreate() {
        super.onCreate();
        boolean autoNat = MyApplication.getBoolean(Constant.KEY_IS_OPEN_AUTO_NAT);
        boolean signal = MyApplication.getBoolean(Constant.KEY_IS_OPEN_SIGNAL);

        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 300, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        // 打开常驻通知
//        Notification notification =
//                new Notification.Builder(this)
//                        .setContentTitle("连接蓝牙自动开启热点")
//                        .setSmallIcon(R.mipmap.ic_launcher)
//                        .setContentIntent(pendingIntent)
//                        .setTicker("关闭")
//                        .build();
        String channelId = null;
        // 8.0 以上需要特殊处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channelId = createNotificationChannel("kim.hsl", "ForegroundService");
        } else {
            channelId = "";
        }

        StringBuilder content = new StringBuilder();
        if (autoNat){
            content.append("连接(").append(MyApplication.getString(Constant.KEY_BLUETOOTH_NAME)).append(")蓝牙将自动开启热点");

            if (signal) {
                content.append("\n");
            }
        }
        if (signal) {
            content.append("显示手机信号");
        }




        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
        Notification notification = builder.setOngoing(true)
                .setSmallIcon(R.mipmap.logo)
                .setPriority(NotificationCompat.PRIORITY_MAX)
//                .setContentTitle(content)
                .setContentTitle("服务正在运行")
                .setContentText(content)
                .setCategory(Notification.CATEGORY_SERVICE)
                .setOngoing(true)
                .setContentIntent(pendingIntent)
                .build();

        startForeground(ONGOING_NOTIFICATION_ID, notification);

        Toast.makeText(this, "打开服务", Toast.LENGTH_SHORT).show();

        if (autoNat) {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
            intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
            intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
            registerReceiver(new BluetoothStateBroadcastReceive(), intentFilter);
        }

        if (signal) {
            if (!hasSimCard(this)) {
                LogUtil.e("getMobileNetworkSignal: no sim card");
                return;
            }

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.width = 200;
            lp.height = 50;
            lp.gravity = Gravity.TOP | Gravity.START;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                lp.type = WindowManager.LayoutParams.TYPE_PHONE;
            }
            lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
            lp.format = PixelFormat.RGBA_8888;


            tvSignal = new TextView(getApplicationContext());
            WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
            tvSignal.setGravity(Gravity.CENTER);
            windowManager.addView(tvSignal, lp);
            phoneStateListener = new PhoneStateListener() {

                @Override
                public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                    super.onSignalStrengthsChanged(signalStrength);
                    String json = JSON.toJSONString(signalStrength);
                    SignalBean sin = JSON.parseObject(json, SignalBean.class);
                    if (tvSignal != null) {
                        tvSignal.setText(String.valueOf(sin.getLteSignalStrength()));
                    }
                    LogUtil.e("signalInfo:: " + JSON.toJSONString(signalStrength) + "");
//                mainHandler.postDelayed(refreshSignalRunnable, 400);
                }
            };
            mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            mainHandler = new Handler(Looper.getMainLooper());
            refreshSignalRunnable = new Runnable() {
                @Override
                public void run() {
                    refreshSignal();
                }
            };
            refreshSignal();
        }

    }


    public void refreshSignal() {
        if (mTelephonyManager != null && phoneStateListener != null) {
            mTelephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        }
    }


    @Override
    public void onDestroy() {
        Toast.makeText(this, "关闭服务", Toast.LENGTH_SHORT).show();
        stopForeground(true);
        super.onDestroy();
    }

    /**
     * 创建通知通道
     *
     * @param channelId
     * @param channelName
     * @return
     */
    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel(String channelId, String channelName) {
        NotificationChannel chan = new NotificationChannel(channelId,
                channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        service.createNotificationChannel(chan);
        return channelId;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    /**
     * 判断是否包含SIM卡
     *
     * @return 状态
     */
    public boolean hasSimCard(Context context) {
        TelephonyManager telMgr = (TelephonyManager)
                context.getSystemService(Context.TELEPHONY_SERVICE);
        int simState = telMgr.getSimState();
        boolean result = true;
        switch (simState) {
            case TelephonyManager.SIM_STATE_ABSENT:
            case TelephonyManager.SIM_STATE_UNKNOWN:
                result = false; // 没有SIM卡
                break;
        }
        return result;
    }
}
